/**
 * This class contains the methods for converting a temperature from Celsius to Fahrenheit and vise versa
 * 
 * @author John Haley
 */
package com.est.android.temperature;

import com.est.android.temperature.R;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

public class Convert extends Activity {
	private EditText txtTemperature;
	
    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        txtTemperature = (EditText) findViewById(R.id.TxtTemperature);
    }
    
    /**
     * Handles what the program does when user clicks on "Calculate" button
     * @param view The view which contains the "Calculate" button
     */
    public void Calculate_OnClick(View view){
    	switch(view.getId()) {
    	case R.id.BtnCalculate:
    		RadioButton celsiusButton = (RadioButton)findViewById(R.id.RdbCelsius);
    		RadioButton fahrButton = (RadioButton)findViewById(R.id.RdbFahrenheit);
    		float inputValue;
    		String temperature = txtTemperature.getText().toString();
    		
    		try {
    			inputValue = Float.parseFloat(temperature);

        		if(celsiusButton.isChecked()) {
        			txtTemperature.setText(String.valueOf(convertFahrToCelsius(inputValue)));
        		}
        		else {
        			txtTemperature.setText(String.valueOf(convertCelsiusToFahr(inputValue)));
        		}
        		
        		if(fahrButton.isChecked()){
        			fahrButton.setChecked(false);
        			celsiusButton.setChecked(true);
        		}
        		else {
        			fahrButton.setChecked(true);
        			celsiusButton.setChecked(false);
        		}
    		} 
    		catch (NumberFormatException ex) {
    			Toast.makeText(this, "Please enter a valid number", Toast.LENGTH_LONG).show();
    		}
    		
    	}
    }
    
    /**
     * Takes the passed value and converts it from Fahrenheit to Celsius 
     * @param fahr The value to be converted in Degrees Fahrenheit
     * @return The converted value in Degrees Fahrenheit
     */
    private float convertFahrToCelsius(float fahr) {
    	return ((fahr - 32) * 5/9);
    }
    
    /**
     * Takes the passed value and converts it from Celsius to Fahrenheit
     * @param celsius The value to be converted in Degrees Celsius
     * @return The converted value in Degrees Celsius
     */
    private float convertCelsiusToFahr(float celsius) {
    	return ((celsius * 9) / 5) + 32;
    }
}